﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Linq;

namespace Common
{
    public class Invocator
    {
        public static Object Invoke(FunctionInfo info, Object[] parameters)
        {
            return Invoke(info, null, parameters);
        }

        public static Object Invoke(FunctionInfo info, Object[] constructorParameters, Object[] parameters)
        {
            Object result = null;

            String assemblyName = info.AssemblyPath;    // Example: "C:\\CommonTestLib.dll";
            String className = info.ClassName;          // Example: "CommonTest.CommonTestLib";
            String methodName = info.MethodName;        // Example: "GetItems";

            Assembly asm = Assembly.LoadFile(assemblyName);
            Type type = asm.GetType(className);
            MethodInfo mi = type.GetMethod(methodName);

            if (mi.IsStatic)
            {
                result = mi.Invoke(null, parameters);
            }
            else
            {
                Object obj = null;

                if (constructorParameters != null && constructorParameters.Length > 0)
                {
                    Type[] constructorParameterTypes = new List<Object>(constructorParameters)
                        .Select(o => o.GetType()).ToArray();
                    ConstructorInfo constructor = type.GetConstructor(constructorParameterTypes);
                    obj = constructor.Invoke(constructorParameters);
                }
                else
                {
                    obj = asm.CreateInstance(type.FullName);
                }

                result = mi.Invoke(obj, parameters);
            }

            return result;
        }
    }
}
